/**
 * Created by Toma on 2016/9/2.
 * 多文件上传,预览
 */

// 创建文件地址
function createObjectURL(blob) {
  if (window.URL) {
    return window.URL.createObjectURL(blob);
  } else if (window.webkitURL) {
    return window.webkitURL.createObjectURL(blob);
  } else {
    return null;
  }
}
// 释放文件
function revokeObjectURL(url) {
  if (window.URL) {
    window.URL.revokeObjectURL(url);
  } else if (window.webkitURL) {
    window.webkitURL.revokeObjectURL(url);
  }
}


function init() {
  var fileEle = document.getElementById('file');
  var box = document.getElementById('box');
  var boxs = document.getElementsByClassName('box');
  var droptarget = document.getElementById('drop');
  var sub = document.getElementById('sub');

  // FileReader
  function fileRead(event) {
    // 通过 ele.files 获取文件列表的信息
    var filelist = event.target.files;

    // reader = new FileReader() 对象 包含文件的原始信息和方法
    if (filelist) {
      var reader = new FileReader();
      reader.readAsDataURL(filelist[0]);
      reader.onload = function () {
        var result = reader.result;
        box.style.background = 'url(' + result + ') no-repeat center/cover';
      };
    }
  }

  fileEle.addEventListener('change', fileRead);


  // creatURL
  function creatURL() {
    var filelist = event.target.files;
    if (filelist) {
      [].forEach.call(boxs, (ele, i) => ele.style.background = 'url(' + createObjectURL(filelist[i]) + ') no-repeat center/cover');
    }
  }

  // fileEle.addEventListener('change', creatURL);


  /**
   * 读取拖放的文件
   * event.dataTransfer.files 被放置的文件
   */
  function handleEvent(event) {
    event.preventDefault();
    if (event.type == "drop") {
      droptarget.style.background = 'url(' + createObjectURL(event.dataTransfer.files[0]) + ') no-repeat center/cover';
    }
  }

  droptarget.addEventListener('dragenter', handleEvent);
  droptarget.addEventListener('dragover', handleEvent);
  droptarget.addEventListener('drop', handleEvent);


  /**
   * Ajax上传文件
   * FormData 文件对象
   */
  function subFile() {
    if (fileEle.files.length) {
      var data = new FormData();
      var xhr = new XMLHttpRequest();
      data.append('file', fileEle.files[0]);

      xhr.open('post', 'server.php', true);
      // multipart/form-data
      // 设置一个自定义请求信息 毫无意义
      xhr.setRequestHeader('X_FILE','image');
      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status >= 200) {
          console.log(xhr.responseText);
        }
      };
      xhr.send(data);
    }
  }

  sub.addEventListener('click', subFile);
}

window.addEventListener('DOMContentLoaded', init, false);

